import storage from 'store'
import { login, getInfo } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      const oauthParam = {}
      oauthParam.grant_type = 'password'
      oauthParam.scope = 'all'
      oauthParam.username = userInfo.username
      oauthParam.password = userInfo.password
      return new Promise((resolve, reject) => {
        login(oauthParam).then(response => {
          if (response && response.access_token) {
            // 登录成功
            const accessToken = response.access_token
            storage.set(ACCESS_TOKEN, accessToken, response.expires_in)
            commit('SET_TOKEN', accessToken)
            resolve(true)
          } else {
            resolve(false)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.data
          if (!result) {
            reject(new Error('响应的用户信息为空'))
          }
          const roles = {}
          if (result.roles && result.permissions.length > 0) {
            roles.permissions = result.permissions
            commit('SET_ROLES', roles)
            commit('SET_INFO', result)
          } else {
            reject(new Error('用户的角色信息为空'))
          }
          console.log(result.avatar)
          commit('SET_NAME', { name: result.name, welcome: welcome() })
          commit('SET_AVATAR', result.avatar)

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        storage.remove(ACCESS_TOKEN)
        resolve()
      })
    }

  }
}

export default user
